import axiosObj from "/component/interceptor.js";
import { createGlobalWebsocket, createdChatWebsocket } from "../../component/websocket.js";
new Vue({
    el: '#app',
    data() {
    return {
        is_commodity_table_visiable:false,
        is_order_table_visiable:false,
        is_message_visiable:false,
        is_add_form_visiable:false,
        is_modify_form_visiable:false,
        is_detail_table_visiable:false,
        commodity_form_data:[],
        commodity_data:[],
        order_data:[],
        add_form_data: {
            name: '',
            detail: '',
            imagePath: '',
            type: '',
            price: '',
            stock: '',
            // 其他表单字段
        },
        modify_form_data:{
            id: '',
            name: '',
            detail: '',
            imagePath: '',
            type: '',
            price: '',
            stock: '',
            // 其他表单字段
        },
        order_dict : {},
        detail_order_info :[],
        out_of_stock_row:null,
        sellerAvatar: '',
        sellerId: 0,
        sellerName: '',
        chatVisible: false,
        // 聊天列表,  { key: sellerId(Number), value: { id: 1, name: '', avatar: ''} }
        chatList: new Map(),
        // 建立的通信对象
        golbalWebsocket: null,
        selectedChatSocket: null,
        // 输入消息
        inputMsg: '',
        sendBtnDisabled: true,
        // 选中的聊天窗口, 结构为 { id: 1, name: '', avatar: ''}
        selectedChat: null,
        // 聊天记录，结构为 { key: sellerId(Number), value: [ Message对象1, Message对象2 ] }
        chatHistory: new Map(),
        // 聊天窗口强制重新渲染
        refreshKey: Math.random()
    };
    },
    watch: {
        // 聊天输入框
        inputMsg(val) {
            if(val === '') {
                this.sendBtnDisabled = true;
            }
            else {
                this.sendBtnDisabled = false;
            }
        }
    },
    async created() {
        this.show_commodity_table();
        // 获取用户头像
        await this.getSellerInfo();
        // 建立全局websocket
        this.golbalWebsocket =  createGlobalWebsocket(this.sellerId);
        this.golbalWebsocket.onmessage = this.globalMessage;
        this.get_all_chat();

        // this.getSenderInfo(1);
        // this.getSenderInfo(2);
        // this.getSenderInfo(9);
    },
    beforeDestroy() {
        if(this.golbalWebsocket) this.golbalWebsocket.close();
        if(this.selectedChatSocket) this.selectedChatSocket.close();
    },
    methods: {
        // 打开聊天窗口
    openChat() {
        this.chatVisible = true;
    },
    get_all_chat(){
        axiosObj({
            method: "post",
            url: "/websocket/ids",
        })
            .then(({ data }) => {
                if(data.code === 1000) {
                    console.log(data.data);
                    data.data.forEach(async(id) => {
                        console.log(id);
                        await this.getSenderInfo(id);
                    })
                }
            })
    },
    async getSellerInfo(){

        // this.sellerId = 7;
        // this.sellerAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png';
        // this.sellerName = '商家1';

        // 由于 ws 送达的消息只有 id 字段，所以需要再次请求获取发送方的头像店铺名等信息
        // 根据userID获取user信息接口不对
        await axiosObj({
            method: "get",
            url: "/seller/search/information",
            params: {
                Id: -1
            }
        })
            .then(({ data }) => {
                if(data.code === 1000) {
                    this.sellerId = data.data.id;
                    this.sellerAvatar = data.data.avatar;
                    this.sellerName = data.data.name;
                    console.log("本商家信息")
                    console.log(this.sellerId, this.sellerAvatar, this.sellerName)
                }
                else {
                    console.log("获取商家信息失败，状态码：" + data.code);
                }
            })
    },
    globalMessage({ data }) {
        console.log('Message push: ', data);
        console.log(Array.isArray(data), data);
        // 消息加入消息池中， chaList 结构 { key: sellerId, value: { id: 111, name: '', avatar: '' } }
        // 这里存储的是全局websocket接收到的消息发送者的列表，这样用户打开Messages就能看到发送了消息的商家
        const data_array = JSON.parse(data);
        data_array.forEach(async ({ senderId }, index) => {
            // 若商家之前不再用户的聊天列表中，就去获取商家的头像、名字等信息
            if (!this.chatList.get(senderId)) {
                // console.log("执行了吗")
                await this.getSenderInfo(senderId);
            };
            // 右上角消息提醒
            console.log("senderId"+senderId)
            this.$notify({
                title: 'New Message',
                message: `You have a message from ${this.chatList.get(senderId).name}`,
                offset: index * 75,
                duration: 6000
            });
        });
    },
    // 获取聊天对象信息，并添加在 chatList 中
    async getSenderInfo(userId) {
        console.log("getSenderInfo")
        // 由于 ws 送达的消息只有 id 字段，所以需要再次请求获取发送方的头像店铺名等信息
        // 根据userID获取user信息接口不对
        await axiosObj({
            method: "get",
            url: "/seller/search/information",
            params: {
                Id: userId
            }
        })
            .then(({ data }) => {
                if(data.code === 1000) {
                    console.log("getSenderInfo成功，状态码：" + data.code);
                    this.chatList.set(userId, data.data);
                    console.log("sender信息")
                    console.log(this.chatList);
                }
                else {
                    console.log("getSenderInfo失败，状态码：" + data.code);
                    // const test_data = {
                    //                     id: 1,
                    //                     name: 'zhangsan',
                    //                     avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
                    // }
                    // this.chatList.set(userId, test_data);
                    console.log(this.chatList)
                }
            })
    },
    // 选择指定聊天窗口，建立一对一通信
    selectChat(chat) {
        console.log("selectChat 运行了吗")
        // 重复选择同一聊天，不进行任何操作
        if (this.selectedChat && chat.id === this.selectedChat.id) return;

        // 将上一个通信连接关闭
        if (this.selectedChat !== null) {
            let prevItem = document.getElementById(this.selectedChat.id);
            prevItem.classList.remove('selected-chat');
            this.selectedChatSocket.close();
        };

        // 建立新通信
        this.selectedChat = chat;
        let item = document.getElementById(chat.id);
        item.classList.add('selected-chat');
        // this.selectedChatSocket = createdChatWebsocket(chat, this.userId);
        this.selectedChatSocket = createdChatWebsocket({id:this.sellerId}, chat.id);


        // 根据连接状态判断
        if (this.selectedChatSocket.readyState === 3 || this.selectedChatSocket.readyState === 2) {
            this.chatVisible = false;
            this.sendBtnDisabled = true;
            this.$message({
                message: 'Get message failed, please check the network, or try again later',
                type: 'warning'
            });
        }
        else {
            // 存储聊天信息
            if (!this.chatHistory.get(chat.id)) {
                this.chatHistory.set(chat.id, []);
            };
            // 挂载消息处理函数
            this.selectedChatSocket.onmessage = this.receiveMessage;
            // 挂载通信关闭处理函数
            this.selectedChatSocket.onclose = this.closeChat;
        };
    },
    // 发送聊天消息
    sendMessage() {
        console.log('sendMessage: ', this.inputMsg);
        // 检查连接状态
        if(this.selectedChatSocket.readyState === 2 || this.selectedChatSocket.readyState === 3) {
            this.$message({
                message: 'Please check the network, or try again later',
                type: 'warning'
            });
        }
        else {
            this.selectedChatSocket.send(this.inputMsg);
            this.inputMsg = '';
        }
    },
    // 获取聊天窗口消息
    receiveMessage(event) {
        const data = JSON.parse(event.data);
        console.log('receiveMessage: ', data);
        // 具体聊天内容，即 message 类型
        if (data.type === 'message') {
            let userId = this.selectedChat.id;
            let chatHistory = this.chatHistory.get(userId);
            this.chatHistory.set(userId, chatHistory.concat(data.messages));
            console.log('ChatHistory: ', this.chatHistory.get(userId));
            this.refreshKey = Math.random();
        };
        // 自动滚动到底部
        this.$nextTick(() => {
            this.scrollTop();
        });
    },
    // 聊天窗口自动滑动到底部
    scrollTop () {
        const chatLines = document.getElementsByClassName('chat-lines') || null;
        const innerContent = document.getElementsByClassName('chat-one-line-container') || null;
        if (chatLines && innerContent) {
            chatLines[0].scrollTo(0, innerContent[0].scrollHeight);
        };
    },
    // 聊天消息时间格式化
    formatDate (secs) {
        let time = (new Date(secs)).toLocaleTimeString('it-IT');
        return `${time.slice(0, 2)}:${time.slice(3, 5)}`;
    },
    closeChat() {
        // 清除聊天缓存
        this.chatHistory.set(this.selectedChat.id, []);
    },
    close_all_table(){
        this.is_commodity_table_visiable=false;
        this.is_order_table_visiable=false;
        this.is_message_visiable=false;
    },
    show_commodity_table(){
        this.close_all_table();
        axiosObj.get("/seller/product/show")
            .then(response => {
                if (response.data.code === 1000) {
                    console.log(response.data);
                    const data = response.data.data;
                    this.commodity_data = data.map(commodity => {
                        return {
                            name : commodity.name,
                            detail : commodity.detail,
                            image : commodity.imagePath,
                            type : commodity.type,
                            price : commodity.price,
                            stock : commodity.stock,
                            sold : commodity.sold,
                            id : commodity.id,
                        };
                    });
                } else {
                    console.log("chucuole");
                    this.$message.error(response.data.msg)
                }
            })
            .catch(error => {
                this.$message.error(error.msg);
                console.error(error);
                // 处理错误
            });
        this.is_commodity_table_visiable=true;
    },
    show_add_form(){
        this.is_add_form_visiable=true;
    },
    handleMenuSelect(index) {
        this.activeIndex = index;
    },
    show_order_table(){
        this.close_all_table();
        this.is_order_table_visiable=true;
        axiosObj.get("/seller/order/show")
            .then(response => {
            if(response.data.code==1000){
                console.log(response.data.data);
                this.order_dict = {};
                this.order_data=response.data.data.map(order=>{
            // 初始化订单信息
            let orderInfo = {
                order_id: 0,
                buyer_id: null,
                order_time: null,
                total_amount: 0,
                status: null,
                customername: null,
                address: null,
                phone: null,
                items: [], // 存储商品信息的数组
                returnInfo: null,
            };
            const statusMap = {
                1: "Placed",
                2: "Paid",
                3: "Shipped",
                4: "Delivered",
                5: "Received"
            };

            // 提取订单ID、买家ID、下单时间
            orderInfo.order_id = order.orderInfo[0].orderId;
            orderInfo.buyer_id = order.orderInfo[0].buyerId;
            orderInfo.order_time = new Date(order.orderInfo[0].orderTime).toLocaleString();
            orderInfo.status = statusMap[order.orderInfo[0].status];
            orderInfo.status_return = order.orderInfo[0].statusReturn
            // 收获人姓名 收货地址 联系方式
            orderInfo.customername = order.orderInfo[0].customername;
            orderInfo.address = order.orderInfo[0].address;
            orderInfo.phone = order.orderInfo[0].phone;
            order.orderInfo.forEach(item => {
                // 提取商品信息
                let itemInfo = {
                    name: item.name,
                    detail: item.detail,
                    number: item.number,
                    price: item.price,
                    type: item.type,
                    image: item.imagePath
                };
                orderInfo.items.push(itemInfo);
                // 计算订单金额
                orderInfo.total_amount += item.price * item.number;
            });
            orderInfo.returnInfo = order.returnInfo
            this.order_dict[orderInfo.order_id] = orderInfo;
            return orderInfo;
                })

                console.log(this.order_data)
            }
            else {
                console.log("出错了");
                this.$message.error(response.data.msg)
            }
        }).catch(error => {
            this.$message.error(error.msg);
            console.error(error);
        })
    },
    show_detail(order) {
        // 根据订单ID从order_dict中获取对应的订单信息
        const orderInfo = this.order_dict[order.order_id];
        
        // 将订单信息赋值给订单详情对话框组件
        this.detail_order_info = orderInfo.items;

        // 显示订单详情对话框
        this.is_detail_table_visiable = true;
    },
    shipped(order) {
        // 发送请求将订单标记为已发货
        const orderId = order.order_id; // 你的订单ID
        const formData = new URLSearchParams();
        formData.append('orderId', orderId);
        console.log(orderId);
        axiosObj.post("/seller/order/Ship/${orderId}", formData)
            .then(response => {
                if (response.data.code === 1000) {
                    // 标记成功
                    // this.$message.success("订单已成功标记为已发货");
                    this.show_order_table();

                    const h = this.$createElement;

                    this.$notify({
                    title: 'Order shipped successfully',
                    });
                } 
                else {
                    console.log("错误响应代码"+response.data.code);
                    // this.$message({message: "发货失败", type: "error"})
                    this.show_order_table();

                    const h = this.$createElement;

                    this.$notify({
                    title: 'Error! Shipping failed',
                    });
                }
            })
            .catch(error => {
                // this.$message({message: "出错了", type: "error"})
                this.show_order_table();

                const h = this.$createElement;

                this.$notify({
                title: 'Error! Shipping failed',
                });
                console.error(error);
            })
    },
    out_of_stock(row) {
        // 发送请求将商品下架
        
        const pro_id = row.id;
        const formData = {"productId":pro_id}
        axiosObj.post("/seller/product/check", formData)
            .then(response => {
                if (response.data.code === 7007)
                {//订单号为空，说明该商品没有在未发货前的订单中使用过，可以下架
                    console.log(response.data.data)
                    this.comfirm_out_of_stock(row);
                }
                else if (response.data.code === 1000)
                {//订单号不为空，说明该商品在未发货前的订单中使用过，需要确认
                    console.log(response.data.data)
                    this.$confirm('This product is included in these orders (either paid or not shipped):'+response.data.data+' Do you confirm to take it off the shelves?', 'tips', {
                        confirmButtonText: 'confirm',
                        cancelButtonText: 'cancel',
                        type: 'warning'
                    }).then(() => {
                        this.comfirm_out_of_stock(row);
                      }).catch(() => {
                        this.$message({
                          type: 'info',
                          message: 'Cancellation of deletion.'
                        });          
                      });
                }
                else{
                    console.log(response.data);
                }
            })
            .catch(error => {
                this.$message.error("Network error, please try again later.");
                console.error(error);
            });
    },
    comfirm_out_of_stock(row = this.out_of_stock_row){
        const pro_id = row.id;
        axiosObj.post("/seller/product/unlist/"+ pro_id)
        .then(response => {
            if (response.data.code === 1000) {
                // 下架成功
                // this.$message.success("商品已成功下架");
                const h = this.$createElement;

                this.$notify({
                title: 'The product has been successfully removed from sale',
                });
                this.show_commodity_table();
            } else {
                // 下架失败
                // this.$message.error("商品下架失败");
                const h = this.$createElement;

                this.$notify({
                title: 'The product removal from sale has failed',
                });
            }
        })
        .catch(error => {
            // this.$message.error("网络错误，请稍后重试");
            const h = this.$createElement;

            this.$notify({
            title: 'The product removal from sale has failed',
            });
            console.error(error);
        });
    },
    modify_product_show(row){
        const pro_id = row.id;
        axiosObj({
            method: "get",
            url: "/seller/product/attributes",
            params: {
                productId: pro_id
            }
        })
        .then(response => {
            if (response.data.code === 1000) {
                console.log(response.data);
                const data = response.data.data;
                this.modify_form_data = data;
            } else {
                console.log("chucuole");
                this.$message.error(response.data.msg)
            }
        })
        .catch(error => {
            this.$message.error(error.msg);
            console.error(error);
            // 处理错误
        });
    this.is_modify_form_visiable=true;
    },
    submit_modify_commodity_form(){
        console.log(this.modify_form_data);
        // 发送POST请求
        axiosObj.post("/seller/product/modify", this.modify_form_data)
        .then(response => {
            console.log(response.data);
            if (response.data.code == 1000) {
                this.$message({message: "修改成功", type: "success"})
                this.show_commodity_table();
            }
            else if (response.data.code == 7005) {
                this.$message({message: response.data.msg, type: "failed"})
            }
            else if (response.data.code == 5000) {
                this.$message({message: "The price and inventory should be of the int type.", type: "failed"})
            }
            else {
                console.log("错误响应代码"+response.data.code);
                this.$message({message: "修改失败（未知错误）", type: "error"})
            }
        })
        .catch(error => {
            this.$message({message: "出错了", type: "error"})
            console.error(error);
        })
        // 处理表单提交逻辑
        console.log('提交表单:', this.add_form_data);
        // 关闭模态框
        this.is_modify_form_visiable = false;
    },
    submit_commodity_form(){
        console.log(this.add_form_data);
        // 发送POST请求
        axiosObj.post("/seller/product/add", this.add_form_data)
        .then(response => {
            console.log(response.data);
            if (response.data.code == 1000) {
                this.$message({message: "添加成功", type: "success"})
                this.show_commodity_table();
            }
            else if (response.data.code == 7005) {
                this.$message({message: response.data.msg, type: "failed"})
            }
            else if (response.data.code == 5000) {
                this.$message({message: "The price and inventory should be of the int type.", type: "failed"})
            }
            else {
                console.log("错误响应代码"+response.data.code);
                this.$message({message: "添加失败", type: "error"})
            }
        })
        .catch(error => {
            this.$message({message: "出错了", type: "error"})
            console.error(error);
        })
        // 处理表单提交逻辑
        console.log('提交表单:', this.add_form_data);
        // 关闭模态框
        this.dialogVisible = false;
        // 延迟一秒清空表单数据
        // setTimeout(() => {
        //     this.$refs.form.resetFields();
        // }, 10000);
        this.is_add_form_visiable = false;
    },
    handleApproveReturn(row, allow){
        let _this = this
        axiosObj({
            method: "post",
            url: "/seller/AgreeReturn/agree",
            data: {
                id: row.returnInfo.id,
                allowed: allow,
                status: row.returnInfo.status
            }
        }).then(function(response) {
            if (response.data.code === 1000) {
                _this.$message({message: "success", type: "failed"})
                _this.show_order_table()
            } else {
                _this.$message({message: response.data.msg, type: "failed"})
            }

        }).catch(error => {
            this.$message({message: "出错了", type: "error"})
            console.error(error);
        })
    },
    handleReceiveReturn(row){

    }
    }

});